package com.ruicar.afs.cloud.manage.common.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.YesOrNoEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.manage.common.condition.MessageTemplateCondition;
import com.ruicar.afs.cloud.manage.common.entity.ManageSmsTemplate;
import com.ruicar.afs.cloud.manage.common.entity.ManageVerifyCode;
import com.ruicar.afs.cloud.manage.common.mapper.ManageSmsTemplateMapper;
import com.ruicar.afs.cloud.manage.common.service.ManageSmsTemplateService;
import com.ruicar.afs.cloud.manage.common.service.ManageVerifyCodeService;
import com.ruicar.afs.cloud.message.sendmessage.config.MessageConfig;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: Lee
 * @date 2020-08-20 10:09:32
 * @description 合同系统短信邮件模板
 */
@Service
@AllArgsConstructor
public class ManageSmsTemplateServiceImpl extends ServiceImpl<ManageSmsTemplateMapper, ManageSmsTemplate> implements ManageSmsTemplateService {

    //短信
    private final String SHORT_MSG = "short-msg";
    //邮件
    private final String EMAIL = "email";
    //0 表示验证码，消息中心要求必须为0
    private final String CHANNEL = "0";

    private final MessageService messageService;
    private final ManageVerifyCodeService manageVerifyCodeService;
    private  final MessageConfig messageConfig;

    @Override
    public IResponse sendMsg(MessageTemplateCondition condition) {
        //查询生效模板
        ManageSmsTemplate messageTemplate = this.getOne(Wrappers.<ManageSmsTemplate>query().lambda()
                .eq(EmptyUtils.isNotEmpty(condition.getTemplateType()), ManageSmsTemplate::getTemplateType, condition.getTemplateType())
                .eq(EmptyUtils.isNotEmpty(condition.getTemplateBusiness()), ManageSmsTemplate::getTemplateBusiness, condition.getTemplateBusiness())
                .eq(EmptyUtils.isNotEmpty(condition.getChannel()), ManageSmsTemplate::getChannel, condition.getChannel())
                .eq(ManageSmsTemplate::getStatus, YesOrNoEnum.yes));
        if (EmptyUtils.isNotEmpty(messageTemplate) && EmptyUtils.isNotEmpty(messageTemplate.getTemplateContent())) {
            String verifyCode = RandomStringUtils.random(4, "0123456789");
            String templateContent=null;
            //自定义，不用替换模板参数
            if(AfsEnumUtil.key(YesOrNoEnum.yes).equals(condition.getWhetherCustom())){
                templateContent=condition.getTemplateContent();
            }else {
                //替换模板参数
                  templateContent = messageTemplate.getTemplateContent()
                        .replace("${custName}", condition.getName())
                        .replace("${number}", condition.getNumber())
                        .replace("${contractNo}", condition.getContractNo())
                        .replace("${verifyCode}", verifyCode);
            }
            SendMessageDto messageDto = new SendMessageDto();
            messageDto.setChannel(messageTemplate.getChannel());
            messageDto.setCode(messageTemplate.getTemplateType().equals(SHORT_MSG) ? messageConfig.getCode() : messageConfig.getCode_0002());
            messageDto.setTimestamp(System.currentTimeMillis() / 1000 + "");
            messageDto.setUid(messageConfig.getUid());
            List<MessageDataDto> dataDtoList = new ArrayList<>();

            MessageDataDto dataDto = new MessageDataDto();
            //邮件、短信公共参数
            dataDto.setPriority(messageTemplate.getPriority());
            dataDto.setDeptId(messageConfig.getDeptId());

            if (messageTemplate.getTemplateType().equals(SHORT_MSG)) {
                //短信参数
                dataDto.setPhone(condition.getNumber());
                dataDto.setSummaryId(condition.getContractNo() + condition.getNumber()+templateContent + DateUtil.format(new Date(), "yyyyMMdd"));
                dataDto.setTemplateId(messageTemplate.getTemplateId());
                dataDto.setSmsContent(templateContent);
                dataDto.setOrigin(messageConfig.getOrigin());
            } else {
                //邮件参数
                dataDto.setReceiver(condition.getNumber());
                dataDto.setSubject(messageTemplate.getSubject());
                dataDto.setEmailContent(templateContent);
            }
            dataDtoList.add(dataDto);
            messageDto.setMessageDataDto(dataDtoList);

            //如果是验证码通道，则保存短信验证码
            if (CHANNEL.equals(condition.getChannel())) {
                ManageVerifyCode code = new ManageVerifyCode();
                code.setContractBusiness(condition.getContractBusiness());
                code.setPhone(condition.getNumber());
                code.setVerifyDate(DateUtil.date());
                code.setVerifyCode(verifyCode);
                manageVerifyCodeService.save(code);
            }

            //发送接口
            SendResultInfoDto sendResultInfoDto = messageService.sendMessageData(messageDto);
            if (EmptyUtils.isNotEmpty(sendResultInfoDto)) {
                if (sendResultInfoDto.getResult().equals(Boolean.TRUE.toString())) {
                    return new IResponse<Boolean>().success("短信发送成功");
                } else {
                    return new IResponse<Boolean>().fail("模板ID为:" + condition.getTemplateType() + "发送失败！原因:" + sendResultInfoDto.getMsgInfo());
                }
            } else {
                return new IResponse<Boolean>().fail("短信接口无响应");
            }
        } else {
            return new IResponse<Boolean>().fail("未找到合同模板！");
        }
    }


}
